package com.atguigu.juc.t14;


import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class T2 {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
            System.out.println("集齐了七颗龙珠，可以召唤神龙了");
        });

        for (int i = 1; i < 8; i++) {
            int num = i;
            new Thread(()->{
                System.out.println(Thread.currentThread().getName() + "正在寻找第" +  num + "颗龙珠");
                try {
                    TimeUnit.SECONDS.sleep(new Random().nextInt(3) + 1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + "找到了，第" +  num + "颗龙珠");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }
    }
}
